package tencent_practice;

import java.util.ArrayList;
import java.util.List;

/**
 * 螺旋矩阵
 */
public class Tencent_54_spiralOrder {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        if (matrix == null || matrix[0].length == 0) {
            return list;
        }
        int m = matrix.length;
        int n = matrix[0].length;
        int i = 0;
        int count = (Math.min(m, n) + 1) / 2;
        while(i < count) {
            for (int j = i; j < n - i; j++) {
                list.add(matrix[i][j]);
            }
            for (int j = i + 1; j < m - i; j++) {
                list.add(matrix[j][n - 1 - i]);
            }
            for (int j = n - i - 2; j >= i && (m - i - 1) != i; j--) {
                list.add(matrix[m - i - 1][j]);
            }
            for (int j = m - i - 2; j >= i + 1 && (n - 1 - i) != i; j--) {
                list.add(matrix[j][i]);
            }
            i++;
        }
        return list;
    }
}
